package middleware

import (
	"time"

	"github.com/gin-gonic/gin"
	"github.com/segmentio/ksuid"
)

const (
	TracerIdHeaderKey   = "X-Trace-Id"
	TracerTimeHeaderKey = "X-Response-Time"
)

// Tracer 全链路跟踪Tracer
func Tracer(ctx *gin.Context) {
	traceID := getTraceId(ctx)
	ctx.Set(TracerIdHeaderKey, traceID)
	ctx.Writer.Header().Add(TracerIdHeaderKey, traceID)
	ctx.Writer.Header().Add(TracerTimeHeaderKey, time.Now().Format(time.RFC3339))
	ctx.Next()
}

// getTraceID Create trace id with UUID4
func getTraceId(c *gin.Context) string {
	traceID := c.Request.Header.Get(TracerIdHeaderKey)
	if traceID == "" {
		traceID = ksuid.New().String()
	}
	return traceID
}
